package cn.com.headfree.util;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

public class ExcelExportUtil {

    private static Logger log = Logger.getLogger(ExcelExportUtil.class);

    private ExcelExportUtil() {
    }

    /**
     * 生成sheet并导入内容 传入工作簿，创建sheet
     *
     * @param workBook
     * @param headers
     * @param content
     * @param sheetName
     * @return
     */
    public static XSSFWorkbook exportExcel(XSSFWorkbook workBook, String[] headers, String[][] content, String sheetName, Integer type) {

        XSSFCellStyle cellStyle = workBook.createCellStyle();
        //设置标题单元格样式
        XSSFCellStyle cellStyleHeader = workBook.createCellStyle();
        cellStyleHeader.setAlignment(HorizontalAlignment.CENTER);
        cellStyleHeader.setVerticalAlignment(VerticalAlignment.CENTER);

        cellStyleHeader.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
        cellStyleHeader.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
        cellStyleHeader.setBorderTop(CellStyle.BORDER_THIN);// 上边框
        cellStyleHeader.setBorderRight(CellStyle.BORDER_THIN);// 右边框
        cellStyleHeader.setFillForegroundColor(new XSSFColor(new java.awt.Color(156, 195, 230)));//设置背景色
        cellStyleHeader.setFillPattern(CellStyle.SOLID_FOREGROUND);//填充模式

        //水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框

        XSSFSheet sheet = workBook.createSheet(sheetName);
        sheet.setVerticallyCenter(true);
        XSSFRow row = sheet.createRow(0);
        for (int i = 1; i < headers.length; i++) {
            XSSFCell cell = row.createCell(i - 1);
//            sheet.autoSizeColumn(i);
            sheet.setColumnWidth(i - 1, 30 * 256);//设置宽度为30字节
            cell.setCellValue(headers[i]);
            cell.setCellStyle(cellStyleHeader);
//            cell.setCellStyle(cellStyle);
        }

        //须要合并的行数
        int rowNum = 0;

        for (int i = 0; i < content.length; i++) {
            row = sheet.createRow((int) i + 1);//从第二行开始添加内容

            //写入数据
            for (int j = 1; j < content[i].length; j++) {
                XSSFCell cell2 = row.createCell(j - 1);//在第一列创建表格
                cell2.setCellValue(content[i][j]);
                cell2.setCellStyle(cellStyle);
            }

            //记录重复的行数
            //i>0且记录id与前一行的id不相同且本行不是最后一行
            if (i > 0 && content[i][0].equals(content[i - 1][0])) {
                //本行的id与前一行的id相同,rowNum加1
                rowNum++;
                //写入值但不进行合并
//                for (int j = 1; j < content[i].length; j++) {
//                    XSSFCell cell2 = row.createCell(j - 1);//在第一列创建表格
//                    cell2.setCellValue(content[i][j]);
//                    cell2.setCellStyle(cellStyle);
//                }
            } else {
                //本行的id与前一行的id不相同,本行的前一行与其之前的rowNum行进行合并
                rowNum = merGeCell(content, type, sheet, rowNum, i,1);
            }

            //如果是最后一行,对须要合并的行进行合并
            if (i == content.length - 1 && rowNum > 0) {
                rowNum = merGeCell(content, type, sheet, rowNum, i,0);
            }

//            row = sheet.createRow((int) i + 1);//从第二行开始添加内容
//            for (int j = 1; j < content[i].length; j++) {
//                XSSFCell cell2 = row.createCell(j - 1);//在第一列创建表格
//                cell2.setCellValue(content[i][j]);
//                cell2.setCellStyle(cellStyle);
//                //判断后一个值的id是否与前一个值的id相同
//                //制度标准-颁布时间,名称,类别,级别(1,2,3,4)
//                //从第二行开始判断是否要合并
////                    if(content[i][0]==content[i-1][0]){
//                if (i > 0 && content[i][0].equals(content[i - 1][0])) {
//
//                    //如果下一行的id与上一行相等,则合并计数器rowNum加1
//                    rowNum++;
//
//                } else {
//                    //如果id不相等,判断合并行数是否为0,如果不为0则进行合并操作
//                    if (rowNum > 0) {
//                        //导师带徒
//                        if (type == 10 && i > 0) {
//                            //id相同,须要进行合并
//                            if (j < 4) {
////                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + rowNum, j - 1, j - 1);
//                                sheet.addMergedRegion(region0);
//                            }
//                        }
//                        //学术成果
//                        if (type == 12 && i > 0) {
//                            //id相同,须要进行合并
//                            if (j < 8) {
////                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + rowNum, j - 1, j - 1);
//                                sheet.addMergedRegion(region0);
//                            }
//                        }
//                        //标准制定
//                        if (type == 13 && i > 0) {
//                            //id相同,须要进行合并
//                            if (j < 5) {
////                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
//                                CellRangeAddress region0 = new CellRangeAddress(i - 1 - rowNum, i - 1, j - 1, j - 1);
//                                sheet.addMergedRegion(region0);
//                            }
//                        }
//                        //专利
//                        if (type == 14 && i > 0) {
//                            //id相同,须要进行合并
//                            if (j < 4) {
////                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + rowNum, j - 1, j - 1);
//                                sheet.addMergedRegion(region0);
//                            }
//                        }
//                        //技艺革新
//                        if (type == 15 && i > 0) {
//                            //id相同,须要进行合并
//                            if (j < 7) {
////                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + rowNum, j - 1, j - 1);
//                                sheet.addMergedRegion(region0);
//                            }
//                        }
//                        //科技创新
//                        if (type == 16 && i > 0) {
//                            //id相同,须要进行合并
//                            if (j < 8) {
////                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + rowNum, j - 1, j - 1);
//                                sheet.addMergedRegion(region0);
//                            }
//                        }
//                        //项目课题成果
//                        if (type == 17 && i > 0) {
//                            //id相同,须要进行合并
//                            if (j < 5) {
////                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + rowNum, j - 1, j - 1);
//                                sheet.addMergedRegion(region0);
//                            }
//                        }
//                    }
//                }
//
//
//            }
        }
        return workBook;

    }

    //合并
    private static int merGeCell(String[][] content, Integer type, XSSFSheet sheet, int rowNum, int i, int midNum) {
        if (rowNum > 0) {
            //单元格合并
            for (int j = 1; j < content[i].length; j++) {
                //如果id不相等,判断合并行数是否为0,如果不为0则进行合并操作
                //导师带徒
                if (type == 10 && i > 0) {
                    //id相同,须要进行合并
                    if (j < 6) {
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
                        CellRangeAddress region0 = new CellRangeAddress(i + 1 - midNum - rowNum, i + 1 - midNum, j - 1, j - 1);
                        sheet.addMergedRegion(region0);
                    }
                }
                //学术成果
                if (type == 12 && i > 0) {
                    //id相同,须要进行合并
                    if (j < 11) {
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
                        CellRangeAddress region0 = new CellRangeAddress(i + 1 - midNum - rowNum, i + 1 - midNum, j - 1, j - 1);
                        sheet.addMergedRegion(region0);
                    }
                }
                //标准制定
                if (type == 13 && i > 0) {
                    //id相同,须要进行合并
                    if (j < 5) {
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
                        CellRangeAddress region0 = new CellRangeAddress(i + 1 - midNum - rowNum, i + 1 - midNum, j - 1, j - 1);
                        sheet.addMergedRegion(region0);
                    }
                }
                //专利
                if (type == 14 && i > 0) {
                    //id相同,须要进行合并
                    if (j < 6) {
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
                        CellRangeAddress region0 = new CellRangeAddress(i + 1 - midNum - rowNum, i + 1 - midNum, j - 1, j - 1);
                        sheet.addMergedRegion(region0);
                    }
                }
                //技艺革新
                if (type == 15 && i > 0) {
                    //id相同,须要进行合并
                    if (j < 8) {
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
                        CellRangeAddress region0 = new CellRangeAddress(i + 1 - midNum - rowNum, i + 1 - midNum, j - 1, j - 1);
                        sheet.addMergedRegion(region0);
                    }
                }
                //科技创新
                if (type == 16 && i > 0) {
                    //id相同,须要进行合并
                    if (j < 10) {
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
                        CellRangeAddress region0 = new CellRangeAddress(i + 1 - midNum - rowNum, i + 1 - midNum, j - 1, j - 1);
                        sheet.addMergedRegion(region0);
                    }
                }
                //项目课题成果
                if (type == 17 && i > 0) {
                    //id相同,须要进行合并
                    if (j < 7) {
//                                CellRangeAddress region0 = new CellRangeAddress(i, i + 1, j - 1, j - 1);
                        CellRangeAddress region0 = new CellRangeAddress(i + 1 - midNum - rowNum, i + 1 - midNum, j - 1, j - 1);
                        sheet.addMergedRegion(region0);
                    }
                }

            }
            //合并完成后计数器清零
            rowNum = 0;
        }
        return rowNum;
    }

    /*
     * 功能描述: excel导出,创建工作簿，再创建sheet
     * @Author: panl
     * @Date: 2020/4/29 14:51
     */
    public static XSSFWorkbook exportExcel(String[] title, String[][] content, String sheetName) throws Exception {
        XSSFWorkbook workBook = new XSSFWorkbook();
        XSSFCellStyle cellStyle = workBook.createCellStyle();
        //水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        XSSFSheet sheet = workBook.createSheet(sheetName);
        sheet.setVerticallyCenter(true);

        XSSFRow row = sheet.createRow(0);
        for (int i = 0; i < title.length; i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(cellStyle);
        }

        for (int i = 0; i < content.length; i++) {
            row = sheet.createRow((int) i + 1);
            for (int j = 0; j < content[i].length; j++) {
                XSSFCell cell2 = row.createCell(j);
                cell2.setCellValue(content[i][j]);
                cell2.setCellStyle(cellStyle);
            }
        }
        return workBook;
    }

    public static void setResponseHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            // 解决文件乱码
            fileName = URLEncoder.encode(fileName, "UTF8").replaceAll("\\+", "%20");// 其他浏览器
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception e) {
//            log.info("****************4");
            e.printStackTrace();
        }
    }

    /*
     * 功能描述: 根据不同的浏览器进行处理
     * @Author:
     * @Date: 2020/5/19 18:12
     */
    public static String getFileName(String fileName, HttpServletRequest request) throws Exception {
        String agent = request.getHeader("User-Agent");
        System.out.println(agent);
        if (agent.contains("Edge")) {                                        //Edge   已测试
            System.out.println("Edge");
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");//处理空格转为加号的问题
        } else if (agent.contains("Chrome")) {                             //google  已测试
            System.out.println("Chrome");
            fileName = new String(fileName.getBytes(), "iso8859-1");
        } else if (agent.contains("Firefox")) {                            //Firefox  待测试
            System.out.println("Firefox");
            fileName = new String(fileName.getBytes(), "iso8859-1");
        } else if (agent.contains("MSIE") || agent.contains("Trident")) {  //IE11      已测试
            System.out.println("IE");
            //在IE8以后，微软使用了Trident来作为IE浏览器的标志，兼容老的版本
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");//处理空格转为加号的问题
        } else {
            //其余浏览器  可测试并添加
            System.out.println("Other");
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");//待测试
        }
        return fileName;
    }

}
